# -*- coding:utf-8 -*-

from xml.etree.ElementTree import XML, ElementTree, Element
from google.appengine.ext import webapp
from google.appengine.ext.webapp import util
from google.appengine.ext import db
import tweepy
import re
import time
import datetime
import random
import urllib
import urllib2
from passwd import chanhoge as p
#import sys

class ChanReplied( db.Model ):
  id = db.IntegerProperty( required=True )

class Friend( db.Model ):
  id = db.IntegerProperty( required=True )
  count = db.IntegerProperty( required=True )

class Word( db.Model ):
  name = db.StringProperty( required=True )
  mean = db.StringProperty( required=True )
  pos  = db.StringProperty( required=True )
  

class Main:

  consumer_key        = p.consumer_key
  consumer_secret     = p.consumer_secret
  access_token        = p.access_token
  access_token_secret = p.access_token_secret

  service_uri = 'http://jlp.yahooapis.jp/MAService/V1/parse?appid=' + p.appid + '&results=ma,uniq&response=surface,reading,pos,baseform,feature&uniq_filter=9|10&sentence='

  def __init__( self ):
    self.auth = tweepy.OAuthHandler(self.consumer_key, self.consumer_secret)
    self.auth.set_access_token(self.access_token, self.access_token_secret)

  def post( self ):
    api = tweepy.API(auth_handler=self.auth)
    last_id = 0

    obj = ChanReplied.all( ).order( '-id' ).get( )
    if obj:
      last_id = obj.id

    friends = Friend.all( )

    id = 0
    num = 0
    mentions = [ ]

    try:
      for m in api.mentions( ):

        if last_id >= m.id:
          break

        if num > 20:
          break

        if re.match( r'^@chanhoge ', m.text ):

          if m.id > id:
            id = m.id

          mentions.append( m )

          num += 1

      mentions.reverse( )
      for m in mentions:

        words = self.analyse_word( m )

        friend = friends.filter( 'id =', m.user.id ).get( )
        buffer = '@' + m.user.screen_name + ' '

        if friend:
          friend.count += 1
          if re.search( ur'おはよう|こんにちは|こんばんは', m.text ):
            buffer += self.get_greeting( ) + m.user.name + u'さん。話しかけてくれたの' + str(friend.count) + u'回目' + random.choice( [ u'だ', u'です' ] ) + u'ね'
          elif re.search( ur'おやすみ', m.text ):
            buffer += u'おやすみ' + random.choice( [ u'なさい', u'' ] ) + m.user.name + u'さん'
          else:
            buffer += self.gen_message( m, words )
        else:
          friend = Friend( id=m.user.id, count=1 )
          buffer += u'はじめまして' + m.user.name + u'さん。よろしく' + random.choice( [ u'おねがいします', u'ね' ] )

        try:
          api.update_status( buffer, m.id )
        except tweepy.error.TweepError, e:
          print e
        friend.put( )
        time.sleep( 2.0 )

      if random.randint( 0, 9 ) == 0:
        try:
          api.update_status( self.gen_random_message( None ) )
        except tweepy.error.TweepError, e:
          print e

    except Exception, e:
      raise e
    finally:
      if id > 0:
        if obj:
          obj.id = int(id)
        else:
          obj = ChanReplied( id=int(id) )
        obj.put( )

  def get_greeting( self ):
    now = datetime.datetime.utcnow( ) + datetime.timedelta( hours=9 )
    if now.hour > 3 and now.hour <= 9:
      return u'おはよう' + random.choice( [ u'ございます', u'' ] )
    elif now.hour > 9 and now.hour <= 17:
      return u'こんにちは' + ramdom.choice( [ u'', u'ー', u'～' ] )
    else:
      return u'こんばんは' + random.choice( [ u'', u'ー', u'～' ] )

  def analyse_word( self, m ):

    words = [ ]
    
    xml = ElementTree( file=urllib2.urlopen( self.service_uri + urllib.quote( re.sub( r'^@chanhoge ', '', m.text.encode( 'utf-8' ) ) ) ) )
    root = xml.getroot( )

    ma_result = root.find( "{urn:yahoo:jp:jlp}ma_result" )
    word_list = ma_result.find( "{urn:yahoo:jp:jlp}word_list" )

    base_surface = None
    match = False
    for word in word_list.findall( "{urn:yahoo:jp:jlp}word" ):

      w = { 'surface' : '', 'reading' : '', 'pos' : '', 'baseform' : '', 'feature' : '' }
      w[ 'surface' ] = word.find( "{urn:yahoo:jp:jlp}surface" ).text
      w[ 'reading' ] = word.find( "{urn:yahoo:jp:jlp}reading" ).text
      w[ 'pos' ] = word.find( "{urn:yahoo:jp:jlp}pos" ).text
      w[ 'baseform' ] = word.find( "{urn:yahoo:jp:jlp}baseform" ).text
      w[ 'feature' ] = word.find( "{urn:yahoo:jp:jlp}feature" ).text
      words.append( w )

      if match:
        if w[ 'pos' ] == u'形容詞' or w[ 'pos' ] == u'名詞':
          obj = Word( name=base_surface, mean=w[ 'baseform' ], pos=w[ 'pos' ] )
          obj.put( )
          match = False

      if w[ 'pos' ] == u'名詞':
        base_surface = w[ 'surface' ]
      elif ( w[ 'surface' ] == u'は' or w[ 'surface' ] == u'が' ) and w[ 'pos' ] == u'助詞' and base_surface:
        match = True

    return words

  def gen_message( self, m, words ):

    targets = [ ]

    if len( words ) > 2:
      if ( words[ -1 ][ 'pos' ] == u'助詞' and words[ -1 ][ 'baseform' ] == u'か' ) or ( words[ -1 ][ 'baseform' ] == u'?' or words[ -1 ][ 'baseform' ] == u'？' ):
        return u'ごめん' + random.choice( [ u'なさい', u'ね' ] ) + u'。まだ質問を理解できるほど頭が良くない' + random.choice( [ u'んだ', u'の', u'のよ' ] )
      if ( words[ -1 ][ 'pos' ] == u'助詞' and words[ -1 ][ 'baseform' ] == u'かな' ) or ( words[ -2 ][ 'pos' ] == u'助動詞' and words[ -2 ][ 'baseform' ] == u'だ' and words[ -1 ][ 'pos' ] == u'助詞' and words[ -1 ][ 'baseform' ] == u'ね' ):
        return random.choice( [ u'うんうん、そうかも' + random.choice( [ u'', u'ね' ] ), random.choice( [ u'うーん、', u'' ] ) + u'わかんない' + random.choice( [ u'や', u'' ] ), u'ちがう' + random.choice( [ u'と思う', u'んじゃないかな' ] ), u'たぶんね' + random.choice( [ u'ー', u'～', u'' ] ) ] )


    for word in words:
      if word[ 'pos' ] == u'名詞':
        targets.append( word[ 'surface' ] )

    if len( targets ) > 0:
      target = random.choice( targets )
      query = Word.all( )
      results = [ ]
      for w in query.filter( 'name = ', target ).fetch( 20 ):
        results.append( w.mean )
      if len( results ) > 0:
        return target + u'は' + random.choice( results ) + u'らしい' + random.choice( [ u'って', u'わね', u'のよ' ] )

    return self.gen_random_message( m ) 

  def gen_random_message( self, m ):
    r = random.randint( 0, 3 )

    if r == 0:
      buffer = self.get_greeting( )
      if m:
        buffer += m.user.name + u'さん'
      return buffer
    elif r > 0:
      query = Word.all( )
      results = query.fetch(1, int( random.random( ) * query.count( ) ) )
      if len( results ) > 0:
        result = results.pop( )
        buffer = result.name + u'は' + result.mean + u'らしい' + random.choice( [ u'って', u'わね', u'のよ' ] )
        return buffer
      else:
        buffer = self.get_greeting( )
        if m:
          buffer += m.user.name + u'さん'
        return buffer

class MainHandler( webapp.RequestHandler ):

  def __init__( self ):
    self.application = Main( )

  def get( self ):
    self.application.post( )

def main( ):

  application = webapp.WSGIApplication( [ ( '/chanhoge', MainHandler ) ], debug=True )

  util.run_wsgi_app( application )


if __name__ == '__main__':
  main( )

